﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace HappyWPF
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Human h = this.FindResource("human") as Human;    // as返回对象 或者 null
            if (h != null)
            {
                MessageBox.Show(h.Name);
            }
        }

        private void Button2_Click(object sender, RoutedEventArgs e)
        {
            Human h = this.FindResource("human2") as Human;    // 因为Child属性不是字符串类型，所以human2的属性Child不能转换，需要下面重写转换方法
            if (h != null)
            {
                MessageBox.Show("name是" + h.Name + "，child的name是" + h.Child.Name);
            }
        }
    }

    [TypeConverter(typeof(NameToHumanTypeConverter))]
    public class Human
    {
        public string Name { get; set; }
        public Human Child { get; set; }
    }

    /// <summary>
    /// 改变as时类型转换的规则，使可以根据字符串来自动创建一个以字符串为名称的对象
    /// </summary>
    public class NameToHumanTypeConverter : TypeConverter
    {
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string name = value.ToString();
            Human child = new Human();
            child.Name = name;
            return child;
        }
    }
}
